package com.css.apps.base.post.action;

import java.util.ArrayList;
import java.util.List;

import com.css.apps.base.org.model.SOrg;
import com.css.apps.base.user.model.SUser;
import com.css.apps.base.user.model.SUserPost;
import com.css.db.page.Page;
import com.css.db.query.QueryCache;
import com.css.util.ListUtil;
import com.css.util.Messages;
import com.css.util.StringHelper;
import com.css.webbase.webwork.action.UserAction;

@SuppressWarnings("serial")
public class DirPostUser extends UserAction {

	private Page page;
	private String postId;
	
	public DirPostUser() {
		page = new Page();
		page.setCountField("a.uuid");
	}
	
	@SuppressWarnings("unchecked")
	@Override
	protected String userGo() {
		if (StringHelper.isEmpty(postId)) {
			setMessage(Messages.getString("systemMsg.fieldEmpty"));
			return ERROR;
		}
		List<Object[]> userList = null;
		QueryCache qc = new QueryCache("from SUserPost a where a.postId = :postId")
				.setParameter("postId", postId);
		page = qc.page(page);
		List<SUserPost> userOrgIds = qc.list();
		if (ListUtil.isLstNotEmpty(userOrgIds)) {
			userList = new ArrayList<>();
			Object[] uo = null;
			for (SUserPost userorg : userOrgIds) {
				uo = new Object[6];
				uo[0] = userorg.getUuid();
				String userId = userorg.getUserId();
				uo[1] = userId;
				SUser user = QueryCache.get(SUser.class, userId);
				uo[2] = user == null ? "" : user.getRealName();
				SOrg org = QueryCache.get(SOrg.class, user.getOrgId());
				uo[3] = org == null ? "" : org.getName();
				uo[4] = user == null ? "" : user.getActiveStatus();
				userList.add(uo);
			}
		}
		page.setResults(userList);
		loadPage(page);
		return SUCCESS;
	}

	private void loadPage(Page page) {
		List<?> results = page.getResults();
		if (results != null) {
			page.setTotalRows(results.size());
			page.setTotalPages((int) Math.ceil(results.size() * 1.0 / page.getPageSize()));
			int total = results.size();
			int curPage = page.getCurrentPage();
			int pageSize = page.getPageSize();
			if (curPage > page.getTotalPages()) {
				curPage = page.getTotalPages();
			}
			int startIndex = (curPage > 0 ? curPage - 1 : 0) * pageSize;
			if (startIndex > total) {
				startIndex = 0;
			}
			int endIndex = startIndex + pageSize;
			if (endIndex > total) {
				endIndex = total;
			}
			results = results.subList(startIndex, endIndex);
			page.setResults(results);
		}
	}
	
	public String getPostId() {
		return postId;
	}

	public void setPostId(String postId) {
		this.postId = postId;
	}

	public Page getPage() {
		return page;
	}

	public void setPage(Page page) {
		this.page = page;
	}

}
